package com.dlut.controller;

import com.dlut.dto.UserDto;
import com.dlut.pojo.Role;
import com.dlut.pojo.User;
import com.dlut.service.IRoleService;
import com.dlut.service.IUserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService service;

    @Autowired
    private IRoleService roleService;

    @RequestMapping("/query")
    public String query(Model model, UserDto dto) throws Exception {
//        List<User> list = service.queryByPage(dto).getList();
        PageInfo<User> pageInfo = service.queryByPage(dto);
        model.addAttribute("pageModel",pageInfo);
        return "user/user";
    }

    @RequestMapping("/userDispatch")
    public String userDispatch(Integer userId,Model model) throws Exception {
        if (userId != null && userId > 0){
            //当前请求是更新数据
            User user = service.queryById(userId);
            model.addAttribute("user",user);
            List<Integer> ownerRoleIds = service.queryUserRoles(userId);
            model.addAttribute("ownerRoleIds", ownerRoleIds);
        }
        List<Role> list = roleService.query(new Role());
        model.addAttribute("roles", list);

        return "user/updateUser";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(UserDto dto) throws Exception {

        Integer a = service.saveOrUpdate(dto);
        return "redirect:/user/query";
    }

    @RequestMapping("/checkUserName")
    @ResponseBody
    public String checkUserName(User user) throws Exception{
        List<User> list = service.query(user);
        if(list == null || list.size() ==0){
            // 表示根据提交的账号查询不到数据，说明 账号不存在
            return "1";
        }
        return "0";
    }

    @RequestMapping("/deleteUser")
    public String deleteUser(Integer userId) throws Exception {
        service.deleteUser(userId);
        return "redirect:/user/query";
    }

}
